<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\admin\middleware\Auth;
use app\model\CategoryModel;
use app\model\RedisModel;
use think\App;
use think\facade\Db;

class BaseCategory extends Base
{

    protected $middleware = [Auth::class];
    private $categoryModel;

    public $cacheKey = "category:id:";

    private $req;

    private $page;

    private $limit;


    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->req = request()->param();

        $this->page = isset($this->req['page']) ? $this->req['page'] : 1;

        $this->limit = isset($this->req['limit']) ? $this->req['limit'] : 999999;

        $this->categoryModel = new CategoryModel();

        $this->isLogin();
    }

    /*
     * 获取店铺列表
     * */
    public function getList()
    {
        $where = [];
//        if (isset($this->req["category_pid"]) && !empty($this->req["category_pid"])) {
//            $where[] = ["category_pid", "=", $this->req["category_pid"]];
//        } else {
//            $where[] = ["category_pid", "<>", 0];
//        }
        $where = [];
        $where[] = ["category_status","=",1];

        $list = $this->categoryModel->getList($where, $this->page, $this->limit);

        $total = $this->categoryModel->getTotal($where, "");

        return $this->succData($total, $list);

    }


    /*
    * 新增/删除/修改
    * */
    public function edit()
    {
        if (!isset($this->req['category_id']) || empty($this->req['category_id'])) {
            return $this->fail("请选择要修改的商品类别");
        }

        if (!isset($this->req['category_name']) || empty($this->req['category_name'])) {
            return $this->fail("名称不能为空");
        }


        $res = $this->categoryModel->updateOne($this->req['category_id'], [
                'category_name' => $this->req['category_name'],]
        );
        if ($res) {
            $this->delCache($this->req['category_id']);
            return $this->succ();
        } else {
            return $this->fail();
        }
    }


    public function delCache($id)
    {
        $redisModel = new RedisModel();

        return $redisModel->delete($this->cacheKey . $id);
    }


    public function delAllCache()
    {
        $redisModel = new RedisModel();

        return $redisModel->deleteAll($this->cacheKey);
    }
}
